package com.zeus.core.log.config;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import com.zeus.common.log.ZeusLoggerConfig;
import com.zeus.core.log.appender.LogbackMonitorAppender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;

/**
 * Logback配置信息
 *
 * @author f1ybear_wang 2021/6/3  0:15
 */
public class LogbackConfig {
    private final static Logger log = LoggerFactory.getLogger(LogbackConfig.class);

    /**
     * Logback配置信息初始化
     *
     * @return 是否初始化成功
     * @author f1ybear_wang 2021/6/3 0:17
     */
    public static boolean init() {
        try {
            // 添加LogbackMonitorAppender
            LoggerContext logbackContext = (LoggerContext)LoggerFactory.getILoggerFactory();
            ch.qos.logback.classic.Logger logbackLogger =
                logbackContext.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
            if (logbackLogger != null) {
                boolean hasAppender = false;
                Iterator<Appender<ILoggingEvent>> appenderIterator = logbackLogger.iteratorForAppenders();
                // 遍历appender
                while (appenderIterator.hasNext()) {
                    hasAppender = true;
                    Appender<ILoggingEvent> next = appenderIterator.next();
                    // 判断是否已经存在
                    if (next.getClass().isAssignableFrom(LogbackMonitorAppender.class)) {
                        if (log.isInfoEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                            log.info(">>> Zeus日志监控模块, into LogMonitorApplicationListener, logback日志监控配置已经注入appender");
                        }
                        return true;
                    }
                }
                if (hasAppender) {
                    // 添加appender
                    LogbackMonitorAppender logbackMonitorAppender = new LogbackMonitorAppender();
                    logbackMonitorAppender.start();
                    logbackLogger.addAppender(logbackMonitorAppender);
                    if (log.isInfoEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                        log.info(">>> Zeus日志监控模块, into LogMonitorApplicationListener, logback日志监控配置信息初始化完成");
                    }
                    return true;
                }
            }
        } catch (Throwable ignored) {
            // 忽略
        }
        return false;
    }
}
